import pygame
import random
from settings import screen_width, screen_height, black  # 导入你的设置
from sprites import PowerUp, Player, Bullet, Enemy  # 导入你的Sprite类
from menu import Button, draw_text   # 导入你的按钮和绘文本函数
from highscore import save_high_score, load_high_score  # 导入高分保存与读取功能

pygame.init()
pygame.mixer.init()  # 初始化音频模块
hit_sound = None
# 设置背景音乐
try:
    pygame.mixer.music.load("背景音乐.mp3")  # 背景音乐文件名
    pygame.mixer.music.set_volume(0.3 )  # 设置音量（0.0到1.0）
    hit_sound = pygame.mixer.Sound("子弹碰撞.mp3")#碰撞音效
    pygame.mixer.music.play(-1)  # 循环播放背景音乐，-1表示无限循环
except pygame.error as e:
    print("无法加载音频文件:" +e)
    pygame.quit()
    exit(1)

# 设置屏幕
screen= pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("射击游戏")

# 加载背景图片
background_image = pygame.image.load("游戏背景.png").convert()
background_image = pygame.transform.scale(background_image, (screen_width, screen_height))

# 设置帧率
clock = pygame.time.Clock()

def generate_powerup():
    powerup = PowerUp()
    powerups.add(powerup)
    all_sprites.add(powerup)

# 初始化所有的Sprite组
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
bullets = pygame.sprite.Group()
powerups = pygame.sprite.Group()

#道具出现的时间
last_powerup_time = pygame.time.get_ticks()
powerup_interval = 20000


# 创建玩家
player = Player()
all_sprites.add(player)

# 创建一批敌人
for i in range(3):
    enemy = Enemy()
    all_sprites.add(enemy)
    enemies.add(enemy)

# 定义菜单按钮
start_button = Button(screen_width // 2 - 100, screen_height // 2 - 50, 200, 50, "开始游戏")
quit_button = Button(screen_width // 2 - 100, screen_height // 2 + 20, 200, 50, "结束游戏")
continue_button = Button(screen_width // 2 - 100, screen_height // 2 - 50, 200, 50, "继续游戏")
exit_button = Button(screen_width // 2 - 100, screen_height // 2 + 20, 200, 50, "退出游戏")

# 游戏状态变量
game_active = False
game_over = False

# 初始化积分
score = 0
high_score = load_high_score()  # 从文件中加载历史最高分
font = pygame.font.Font("simhei.ttf", 36)  # 使用默认字体, 大小为36

def draw_score(screen, score, high_score):
    text_surface = font.render(f"积分: {score}  最高分: {high_score}", True, (255, 255, 255))
    screen.blit(text_surface, (10, 10))



clock = pygame.time.Clock()
# 游戏主循环
running = True
while running:
    clock.tick(60)  # 每秒刷新60次
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            if not game_active and not game_over:
                if start_button.is_clicked(pos):
                    game_active = True
                    score = 0  # 重置积分
                elif quit_button.is_clicked(pos):
                    running = False
            elif game_over:
                if continue_button.is_clicked(pos):
                    game_active = True
                    game_over = False
                    # 重置游戏
                    all_sprites.empty()
                    enemies.empty()
                    bullets.empty()
                    player = Player()
                    all_sprites.add(player)
                    for i in range(8):  # 这里改成8个敌人
                        enemy = Enemy()
                        all_sprites.add(enemy)
                        enemies.add(enemy)
                    score = 0  # 重置积分
                elif exit_button.is_clicked(pos):
                    running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE and game_active:
                player.shoot(bullets, all_sprites)
            # 检查是否需要生成新的道具
        current_time = pygame.time.get_ticks()
        if current_time - last_powerup_time > powerup_interval and len(powerups) == 0:
            generate_powerup()
            last_powerup_time = current_time

        # 检测玩家是否拾取道具
    powerup_hits = pygame.sprite.spritecollide(player, powerups, True)
    for hit in powerup_hits:
        player.power_up = True
        player.power_up_time = pygame.time.get_ticks()
    if game_active:
        all_sprites.update()

        hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
        for hit in hits:
            score += 1  # 击败敌人，积分加1
            hit_sound.play()
            enemy = Enemy()
            all_sprites.add(enemy)
            enemies.add(enemy)

        hits = pygame.sprite.spritecollide(player, enemies, False)
        if hits:
            game_active = False
            game_over = True
            if score > high_score:
                high_score = score
                save_high_score(high_score)  # 保存新的最高分到文件

        screen.blit(background_image, (0, 0))  # 绘制背景图片
        all_sprites.draw(screen)
        draw_score(screen, score, high_score)  # 绘制积分和历史最高分
    else:
        screen.blit(background_image, (0, 0))  # 绘制背景图片
        if game_over:
            draw_text(screen, "游戏结束", 64, screen_width // 2, screen_height // 4)
            continue_button.draw(screen)
            exit_button.draw(screen)
            draw_score(screen, score, high_score)  # 显示最后的积分和历史最高分
        else:
            draw_text(screen, "射击游戏", 64, screen_width // 2, screen_height // 4)
            start_button.draw(screen)
            quit_button.draw(screen)


    hits = pygame.sprite.groupcollide(enemies, bullets, True, True)
    for hit in hits:
        hit_sound.play()
        enemy = Enemy()
        all_sprites.add(enemy)
        enemies.add(enemy)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()